package com.yunao.service.template;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.yunao.commons.serachcore.core.bean.Article;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;


@Component
public class MailTextTemplate {


    @Autowired
    private SpringTemplateEngine templateEngine;

    public String process(List<Article> articles) {

        Collections.sort(articles, Comparator.comparing(Article::getTitle).reversed());

        Context context = new Context();
        context.setVariable("云奥舆情", createAlarmInfo(articles));
        return templateEngine.process("article.mail", context).replaceAll("&lt;([/]*)B&gt;",
                "<$1em>");
    }

    private MailTextInfo createAlarmInfo(List<Article> articles) {
        MailTextInfo alarmInfo = new MailTextInfo();
        alarmInfo.setSubject("云奥舆情");
        alarmInfo.setTime(DateTime.now().toString("yyyy-MM-dd HH:mm"));
        long negs = articles.stream().filter(article -> "负面".equals(article.getEmotion())).count();
        String statistics = "发送消息 " + articles.size() + " 条，负面消息 " + negs + " 条。";
        alarmInfo.setStatistics(statistics);
        alarmInfo.setArticles(articles);
        alarmInfo.setCancel("http://ssl.esou.me/ab_cancel.do?p=$param");
        return alarmInfo;
    }

}
